package com.thingcom.delinrobot.main.adddevice;


import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.gizwits.gizwifisdk.api.GizWifiSDK;
import com.gizwits.gizwifisdk.enumration.GizWifiDeviceNetStatus;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.gizwits.gizwifisdk.listener.GizWifiSDKListener;
import com.thingcom.delinrobot.Common.Constant;
import com.thingcom.delinrobot.Data.GizManger;
import com.thingcom.delinrobot.R;
import com.thingcom.delinrobot.base.BaseActivity;
import com.thingcom.delinrobot.base.BaseMainFragment;
import com.thingcom.delinrobot.main.Launch.WelcomeMainFragment;
import com.thingcom.delinrobot.main.device.DevicePinFragment;
import com.thingcom.delinrobot.utils.ChangeNameDialog;
import com.thingcom.delinrobot.utils.CommonDialog;
import com.thingcom.delinrobot.utils.MyLog;
import com.thingcom.delinrobot.utils.PreferencesUtil;
import com.thingcom.delinrobot.utils.ToastUtil;
import com.thingcom.delinrobot.view.SimpleToolbar;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.thingcom.delinrobot.Common.Constant.MAIL_NUMBER;
import static com.thingcom.delinrobot.Common.Constant.TOKEN;
import static com.thingcom.delinrobot.Common.Constant.UID;
import static com.thingcom.delinrobot.DelinApplication.PRODUCT_S;


/**
 * author : YuFeng
 * e-mail : 923462992@qq.com
 * date   : 2019/11/13
 */
public class DeviceListFragment extends BaseMainFragment implements Toolbar.OnMenuItemClickListener,GizManger.myGizWifiDeviceListener {
    private static final long WAIT_TIME = 2000L;
    @BindView(R.id.btn_add_device)
    Button btnAddDevice;
    @BindView(R.id.cl_have_devices)
    ConstraintLayout clHaveDevices;
    @BindView(R.id.cl_no_devices)
    ConstraintLayout clNoDevices;
    private long TOUCH_TIME = 0;
    private PopupWindow popupWindow;
    private View popupview;
    @BindView(R.id.recycler_device)
    RecyclerView recyclerDevice;
    @BindView(R.id.toolbar_device_list)
    SimpleToolbar toolbarDeviceList;
    private List<GizWifiDevice> devices;
    private TextView tvUserName;
    private TextView tvUserOut;
    private String uid;
    private String token;
    private RobotAdapter mAdapter;
    private GizWifiDevice mDevice;
    private String did;
    private DeviceListActivity activity;

    public static DeviceListFragment newInstance() {
        Bundle args = new Bundle();
        DeviceListFragment fragment = new DeviceListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 主动刷新绑定设备列表、指定筛选的设备productKey
        uid = PreferencesUtil.getInstance(getContext()).getString(UID, null);
        token = PreferencesUtil.getInstance(getContext()).getString(TOKEN, null);
        MyLog.i("Activity生命周期", "onCreate: ");
        MyLog.i("设备列表", "DeviceListFragment: " + " uid:" + uid + " token:" + token);

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity = (DeviceListActivity) context;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_main_device_list, container, false);
        popupview = inflater.inflate(R.layout.popup_user_info, container, false);
        tvUserName = popupview.findViewById(R.id.tv_user_name);
        tvUserOut = popupview.findViewById(R.id.tv_user_out);
        unbinder = ButterKnife.bind(this, v);
        initToolbar1(toolbarDeviceList);
        toolbarDeviceList.setOnMenuItemClickListener(this);
        initView();
        MyLog.i("Activity生命周期", "onCreateView: ");
        return v;
    }

    @Override
    public void onResume() {
        super.onResume();
//        GizWifiSDK.sharedInstance().setListener(mListener);
        GizManger.getInstance().setmCallback(this);
        GizWifiSDK.sharedInstance().setListener(mListener);
        if (uid != null && token != null) {
            GizWifiSDK.sharedInstance().getBoundDevices(uid, token);
        }

        MyLog.i("Activity生命周期", "onResume: "+this.toString());
        MyLog.i("寻找设备", "uid:" + uid + " token:" + token);
    }

    @Override
    public void onPause() {
        super.onPause();

        MyLog.i("Activity生命周期", "onPause: "+this.toString());
    }

    @Override
    public void onStop() {
        super.onStop();
        MyLog.i("Activity生命周期", "onStop: "+this.toString());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        MyLog.i("Activity生命周期", "onDestroy: "+this.toString());
    }

    private void popup() {
        // 填充布局并设置弹出窗体的宽,高
        popupWindow = new PopupWindow(popupview,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        // 设置弹出窗体可点击
        popupWindow.setFocusable(true);
        // 设置弹出窗体动画效果
        popupWindow.setAnimationStyle(R.style.user_info_anim);
        // 触屏位置如果在选择框外面则销毁弹出框
        popupWindow.setOutsideTouchable(false);
        // 设置弹出窗体的背景
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        popupWindow.showAtLocation(popupview,
                Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
        String mail = PreferencesUtil.getInstance(getContext()).getString(MAIL_NUMBER, null);
        tvUserName.setText(mail);
        tvUserOut.setOnClickListener(v -> {
            PreferencesUtil.getInstance(getContext()).putString(Constant.MAIL_S, null);
            start(WelcomeMainFragment.newInstance(), 2);
            popupWindow.dismiss();
        });
    }


    private void initToolbar1(SimpleToolbar toolbar) {
        toolbar.setMyLeftIcon(R.drawable.menu_black);
        toolbar.setMinimumHeight(42);
        toolbar.setMyRightIcon1(R.drawable.user);
        toolbar.setBackgroundColor(getResources().getColor(R.color.black_main));
        toolbar.setTitleStyle(getResources().getColor(R.color.toolbar_yellow), 20);
        toolbar.setLeftIconClickListener(view -> {
            start(AboutCompanyFragment.newInstance());
//                if (mOpenDraweListener != null) {
//                    mOpenDraweListener.onOpenDrawer();
//                }
        });
        toolbar.setRightIcon1ClickListener(v -> popup());
    }

    private void initView() {
        devices = new ArrayList<>();
        recyclerDevice.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false));
        mAdapter = new RobotAdapter(devices);
        mAdapter.bindToRecyclerView(recyclerDevice);
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.device_item){
                if (isFastDoubleClick(1000)) {
                    return;
                }
                mDevice = devices.get(position);
                GizManger.getInstance().setDevice(mDevice);
                if (mDevice.isSubscribed()){
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    start(DevicePinFragment.newInstance());
                } else{
                    mDevice.setSubscribe(PRODUCT_S, true);
                }


                //   mDevice.setSubscribe(PRODUCT_S,true);

            } else if (view.getId() == R.id.device_item_delete){
                mDevice = devices.get(position);
                did = mDevice.getDid();
                CommonDialog fragment = CommonDialog.newInstance(getString(R.string.start_tip), getString(R.string.Are_you_sure));
                fragment.setCancelable(false);
                if (getFragmentManager() != null) {
                    fragment.show(getFragmentManager(), "dialog");
                }
                fragment.setOnOkListener(() -> GizWifiSDK.sharedInstance().unbindDevice(uid, token, did));
            }
        });

        mAdapter.setOnItemChildLongClickListener((adapter, view, position) -> {
            mDevice = devices.get(position);
            did = mDevice.getDid();
            String alias = mDevice.getAlias();
            if (alias==null){
                alias = mDevice.getProductName();
            }
            MyLog.i("设备名字", "onItemChildLongClick: "+"alias"+alias);
            ChangeNameDialog changeNameDialog = ChangeNameDialog.newInstance(alias);
            changeNameDialog.setCancelable(false);
            if (getFragmentManager() == null)
                return false;
            changeNameDialog.show(getFragmentManager(), "dialog");
            changeNameDialog.setOnChangeNameListener((name) -> mDevice.setCustomInfo(mDevice.getRemark(),name));


            return false;
        });
    }


    @OnClick(R.id.btn_add_device)
    public void onViewClicked() {
        start(AddDeviceZeroFragment.newInstance());
    }


    private class RobotAdapter extends BaseQuickAdapter<GizWifiDevice, BaseViewHolder> {

        RobotAdapter(@Nullable List<GizWifiDevice> data) {
            super(R.layout.device_online_item_layout, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, GizWifiDevice item) {
            String alias = item.getAlias();
            MyLog.i("name123", "alias: " + alias );
            if (alias.equals("")){
                helper.setText(R.id.tv_device_online, "robot 2 mow");
            } else {
                helper.setText(R.id.tv_device_online, item.getAlias());
            }

            ImageView imageView = helper.getView(R.id.iv_online_device);
            String robotChoose = item.getRemark();
            switch (robotChoose){
                case "0":
                default:
                    imageView.setImageDrawable(Objects.requireNonNull(getContext()).getDrawable(R.drawable.device_type_18));
                    break;
                case "1":
                case "2":
                    imageView.setImageDrawable(Objects.requireNonNull(getContext()).getDrawable(R.drawable.device_type_24));
                    break;
            }
            helper.addOnClickListener(R.id.device_item);
            helper.addOnClickListener(R.id.device_item_delete);
            helper.addOnLongClickListener(R.id.device_item);
        }
    }

    private void updateUI(List<GizWifiDevice> deviceList) {
        devices.clear();
        devices.addAll(deviceList);
        mAdapter.notifyDataSetChanged();
    }


    // 接收设备列表变化上报，刷新UI
    private GizWifiSDKListener mListener = new GizWifiSDKListener() {

        @Override
        public void didDiscovered(GizWifiErrorCode result, List<GizWifiDevice> deviceList) {
            // 提示错误原因
            MyLog.i("寻找设备", "result: " + result);
            //MyLog.i(TAG, "result: " + result.name());
            // 显示变化后的设备列表
            MyLog.i("寻找设备", "discovered deviceList: " + deviceList);
            //一开始的代码
//            for(GizWifiDevice gizWifiDevice : deviceList) {
//                if (gizWifiDevice.getNetStatus() == GizWifiDeviceNetStatus.GizDeviceOffline) {
//                    Log.i(TAG, "didDiscovered: 到了");
//                    deviceList.remove(gizWifiDevice);
//                }
//            }
            List<GizWifiDevice> List = new ArrayList<>();
            for (int i = 0; i < deviceList.size(); i++) {
                GizWifiDevice gizWifiDevice = deviceList.get(i);

                //if (gizWifiDevice.getNetStatus() == GizWifiDeviceNetStatus.GizDeviceOnline||gizWifiDevice.getNetStatus() == GizWifiDeviceNetStatus.GizDeviceControlled){
                if (gizWifiDevice.getNetStatus() == GizWifiDeviceNetStatus.GizDeviceOnline && gizWifiDevice.isBind()&&!gizWifiDevice.isSubscribed()) {
                    List.remove(gizWifiDevice);
                    List.add(gizWifiDevice);
                }

                if (gizWifiDevice.getNetStatus() == GizWifiDeviceNetStatus.GizDeviceOffline  || gizWifiDevice.getNetStatus() == GizWifiDeviceNetStatus.GizDeviceControlled) {
                    List.remove(gizWifiDevice);
                }
            }
            if (List.size() == 0) {
                activity.runOnUiThread(() -> {
                    clNoDevices.setVisibility(View.VISIBLE);
                    clHaveDevices.setVisibility(View.GONE);
                });

            } else {
                activity.runOnUiThread(() -> {
                    clNoDevices.setVisibility(View.GONE);
                    clHaveDevices.setVisibility(View.VISIBLE);
                });

            }
            updateUI(List);
        }

        @Override
        public void didUnbindDevice(GizWifiErrorCode result, String did) {
            if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                // 解绑成功
                MyLog.i("解绑", "didUnbindDevice 成功: " + did);
            } else {

                MyLog.i("解绑", "didUnbindDevice 失败: " + did);
            }
        }


    };

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        return false;
    }

    @Override
    public boolean onBackPressedSupport() {
        if (System.currentTimeMillis() - TOUCH_TIME < WAIT_TIME) {
            BaseActivity.destroyAllOnExit();
        } else {
            TOUCH_TIME = System.currentTimeMillis();
            ToastUtil.showToast(_mActivity, getString(R.string.toast_press_again_exit));
        }
        return true;
    }

    @Override
    public void didSetSubscribe(GizWifiErrorCode result, GizWifiDevice device, boolean isSubscribed) {
        if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
            // 订阅或解除订阅成功
            //       GizManger.getInstance().setDevice(mDevice);
            MyLog.i("订阅", "订阅修改成功：" + "DeviceListFragment"+"isSubscribed: " +isSubscribed );
            if(isSubscribed){
                GizManger.getInstance().removeCallback();
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                start(DevicePinFragment.newInstance());
            }

        } else {
            // 失败
            MyLog.i("订阅", "订阅修改失败：" + this.toString() );
        }
    }


    @Override
    public void didReceiveData(GizWifiErrorCode result, GizWifiDevice device, ConcurrentHashMap<String, Object> dataMap, int sn) {

    }

    @Override
    public void didGetHardwareInfo(GizWifiErrorCode result, GizWifiDevice device, ConcurrentHashMap<String, String> hardwareInfo) {

    }

    @Override
    public void didSetCustomInfo(GizWifiErrorCode result, GizWifiDevice device) {

    }

    @Override
    public void didUpdateNetStatus(GizWifiDevice device, GizWifiDeviceNetStatus netStatus) {

    }
    private static long lastClickTime;
    public static boolean isFastDoubleClick(int a) {
        long time = System.currentTimeMillis();
        if ( time - lastClickTime < a) {
            return true;
        }
        lastClickTime = time;
        return false;
    }
}
